<?php
require_once 'init_app.php';

set_time_limit(0); 

$categories = ORM::factory('category')
                    ->find_all();
foreach ($categories as $category) {
    $ids = array();
    if ($category->childs) {
        $ids = explode(',', $category->childs);    
    }
    $ids[] = $category->id;
    
    DB::query(Database::UPDATE, "UPDATE categories
                             SET min_price = (SELECT MIN(price) FROM products WHERE category_id IN (".implode(',', $ids).") AND price > 0 AND is_available = 1)
                             WHERE id = ".$category->id)->execute();      
}

$tags = ORM::factory('tag')
                ->find_all();
foreach ($tags as $tag) {
    DB::query(Database::UPDATE, "UPDATE tags
                             SET min_price =   (SELECT MIN(products.price) 
                                                FROM products
                                                JOIN product_tags ON (product_tags.product_id = products.id)
                                                WHERE product_tags.tag_id = ".$tag->id."
                                                AND products.price > 0
                                                AND products.is_available = 1)
                             WHERE id = ".$tag->id)->execute();       
}
 
echo "ok\n";